package com.neuedu.util;

import com.alibaba.fastjson.JSONObject;
import com.neuedu.config.NeueduRequest;
import com.neuedu.entity.Customer;
import com.neuedu.vo.ResultJson;
import io.micrometer.common.util.StringUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.core.annotation.Order;
import org.springframework.http.client.support.HttpRequestWrapper;
import org.springframework.stereotype.Component;

import java.io.IOException;


public class AuthorizationFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        if (servletRequest instanceof HttpServletRequest request && servletResponse instanceof HttpServletResponse response) {
            String token = request.getHeader("Authorization");
            if (StringUtils.isNotBlank(token)) {
                try {
                    Customer customer = JwtUtil.getCustomer(token);
                    NeueduRequest neueduRequest = new NeueduRequest(request);
                    neueduRequest.addParameter("openId", String.valueOf(customer.getId()));
                    filterChain.doFilter(neueduRequest, response);
                } catch (Exception ex) {
                    ex.printStackTrace();
                    error(response, ResultJson.unlogin("非法请求"));
                }
            }
        }
    }
    public void error(HttpServletResponse response, ResultJson resultJson) throws IOException {
        response.setHeader("Content-Type", "application/json;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "*");
        response.getWriter().write(JSONObject.toJSONString(resultJson));
    }
}
